<template>
  <view class="main">
    <u-sticky>
      <qualificationAddStep :step="3"/>
    </u-sticky>

    <view class="content">
      <u--form
          labelPosition="left"
          :model="merchantDetail"
          :rules="storeInfoModelRules"
          ref="storeInfoForm"
          labelWidth="87"
          :labelStyle="{fontSize:'26rpx', color: 'rgba(0, 0, 0, 0.7)', padding: '18rpx 0'}"
      >
        <view class="content-item">
          <view class="content-title">上传场地照片</view>
          <u-form-item label=" " prop="shopPhotoAndShopEntrancePhoto" ref="shopPhotoAndShopEntrancePhotoItem" labelWidth="0">
            <view class="upload u-flex u-row-between">
              <u-upload
                  ref="shopPhotoUpload"
                  :fileList="shopPhotoUrlList"
                  @afterRead="photoUploadAfterRead"
                  :name="photoTypeEnum.shopPhoto"
                  :maxCount="1"
                  :width="imgWidth"
                  :height="imgHeight"
                  :maxSize="maxSize"
                  @oversize="bannerOversize"
                  @delete="deletePhoto(photoTypeEnum.shopPhoto)"
              >
                <u--image :showLoading="true" :src="`${baseStaticFileUrl}/image/pages-qualification/shop-photo.png`"
                          :width="imgWidth" :height="imgHeight" @tap.stop.prevent="openUploadDemo(photoTypeEnum.shopPhoto)"/>
              </u-upload>

              <u-upload
                  ref="shopEntrancePhotoUpload"
                  :fileList="shopEntrancePhotoUrlList"
                  @afterRead="photoUploadAfterRead"
                  :name="photoTypeEnum.shopEntrancePhoto"
                  :maxCount="1"
                  :width="imgWidth"
                  :height="imgHeight"
                  :maxSize="maxSize"
                  @oversize="bannerOversize"
                  @delete="deletePhoto(photoTypeEnum.shopEntrancePhoto)"
              >
                <u--image :showLoading="true" :src="`${baseStaticFileUrl}/image/pages-qualification/shop-entrance-photo.png`"
                          :width="imgWidth" :height="imgHeight" @tap.stop.prevent="openUploadDemo(photoTypeEnum.shopEntrancePhoto)"/>
              </u-upload>
            </view>
          </u-form-item>

          <u-form-item label=" " prop="checkStandPhotoAndHandHoldIdCard" ref="checkStandPhotoAndHandHoldIdCardItem" labelWidth="0">
            <view class="upload u-flex u-row-between">
              <u-upload
                  ref="checkStandPhotoUpload"
                  :fileList="checkStandPhotoUrlList"
                  @afterRead="photoUploadAfterRead"
                  :name="photoTypeEnum.checkStandPhoto"
                  :maxCount="1"
                  :width="imgWidth"
                  :height="imgHeight"
                  :maxSize="maxSize"
                  @oversize="bannerOversize"
                  @delete="deletePhoto(photoTypeEnum.checkStandPhoto)"
              >
                <u--image :showLoading="true" :src="`${baseStaticFileUrl}/image/pages-qualification/check-stand-photo.png`"
                          :width="imgWidth" :height="imgHeight" @tap.stop.prevent="openUploadDemo(photoTypeEnum.checkStandPhoto)"/>
              </u-upload>

<!--              <u-upload-->
<!--                  ref="handHoldIdCardUpload"-->
<!--                  :fileList="handHoldIdCardUrlList"-->
<!--                  @afterRead="photoUploadAfterRead"-->
<!--                  :name="photoTypeEnum.handHoldIdCard"-->
<!--                  :maxCount="1"-->
<!--                  :width="imgWidth"-->
<!--                  :height="imgHeight"-->
<!--                  :maxSize="maxSize"-->
<!--                  @oversize="bannerOversize"-->
<!--                  @delete="deletePhoto(photoTypeEnum.handHoldIdCard)"-->
<!--              >-->
<!--                <u&#45;&#45;image :showLoading="true" :src="`${baseStaticFileUrl}/image/pages-qualification/hand-holdId-card.png`"-->
<!--                          :width="imgWidth" :height="imgHeight" @tap.stop.prevent="openUploadDemo(photoTypeEnum.handHoldIdCard)"/>-->
<!--              </u-upload>-->
            </view>
          </u-form-item>
        </view>
      </u--form>
    </view>

    <view class="footer">
      <u-button type="primary" text="提交" :customStyle="nextStepBtnCustomStyle" @click="submit()"/>
    </view>

    <storeInfoComponent ref="storeInfoComponent"/>
  </view>
</template>

<script>
import storeInfoComponent from '@/components/store-info/store-info';
import merchantDetail from '@/common/po/merchant-detail.ts';
import qualificationAddStep from '@/components/qualification-add-step/qualification-add-step';
export default {
  components: {
    qualificationAddStep,
    storeInfoComponent
  },
  data() {
    return {
      qiNiuImgURL: this.$configPath.qiNiuImgURL,
      baseStaticFileUrl: this.$configPath.staticFileUrl,

      maxSize: 3 * 1024 * 1024,
      imgWidth: '330rpx',
      imgHeight: '234rpx',
      nextStepBtnCustomStyle: {
        width: '690rpx',
        height: '88rpx',
        borderRadius: '120px',
        color: '#fff',
        margin: '14rpx auto 0rpx',
      },

      shopPhotoUrlList: [],
      shopEntrancePhotoUrlList: [],
      checkStandPhotoUrlList: [],
      handHoldIdCardUrlList: [],
      photoTypeEnum: {
        shopPhoto: 'shopPhoto',
        shopEntrancePhoto: 'shopEntrancePhoto',
        checkStandPhoto: 'checkStandPhoto',
        // handHoldIdCard: 'handHoldIdCard',
      },


      merchantDetail: merchantDetail,

      storeInfoModelRules: {
        'shopPhotoAndShopEntrancePhoto': {
          type: 'boolean',
          required: true,
          message: '请上传门头、内景照片',
          validator: (rule, value, callback) => {
            return value == true;
          },
        },
        'checkStandPhotoAndHandHoldIdCard': {
          type: 'boolean',
          required: true,
          message: '请上传收银台',
          validator: (rule, value, callback) => {
            return value == true;
          },
        },
      },
      merchantInfoUploadStateEnum: this.$merchantInfoUploadStateEnum,

    }
  },
  onReady() {
    this.$refs.storeInfoForm.setRules(this.storeInfoModelRules)
  },
  onShow(){},
  onLoad(){
    this.getUncommittedMerchantInfo();
  },
  onUnload(){
    uni.$emit('updateMerchantInfo-storeInfo', {
      data: this.merchantDetail
    })
  },
  methods: {
    // 打开上传示例
    openUploadDemo(photoType){
      this.$refs.storeInfoComponent.showPopup(photoType);
    },

    upload(photoType){
      this.$nextTick(() => {
        if (photoType == this.photoTypeEnum.shopPhoto){
          this.$refs.shopPhotoUpload.chooseFile()
        } else if (photoType == this.photoTypeEnum.shopEntrancePhoto){
          this.$refs.shopEntrancePhotoUpload.chooseFile()
        } else if (photoType == this.photoTypeEnum.checkStandPhoto){
          this.$refs.checkStandPhotoUpload.chooseFile()
        }
        // else if (photoType == this.photoTypeEnum.handHoldIdCard){
        //   this.$refs.handHoldIdCardUpload.chooseFile()
        // }
        else {
          getApp().err("启动上传照片不成功")
        }
      })
    },

    initData(data){
      this.merchantDetail = data;

      // 门头照
      if (!this.$u.test.isEmpty(this.merchantDetail.shopPhoto)){
        this.shopPhotoUrlList.length = 0;
        this.shopPhotoUrlList.push({
          status: 'success',
          message: '',
          url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.shopPhoto)
        })
      }
      // 内景照
      if (!this.$u.test.isEmpty(this.merchantDetail.shopEntrancePhoto)){
        this.shopEntrancePhotoUrlList.length = 0;
        this.shopEntrancePhotoUrlList.push({
          status: 'success',
          message: '',
          url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.shopEntrancePhoto)
        })
      }
      // 门头照、内景照是否都上传
      this.checkShopPhotoAndShopEntrancePhoto()

      // 收银台照
      if (!this.$u.test.isEmpty(this.merchantDetail.checkStandPhoto)){
        this.checkStandPhotoUrlList.length = 0;
        this.checkStandPhotoUrlList.push({
          status: 'success',
          message: '',
          url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.checkStandPhoto)
        })
      }
      // 手持身份证照
      // if (!this.$u.test.isEmpty(this.merchantDetail.handHoldIdCard)){
      //   this.handHoldIdCardUrlList.length = 0;
      //   this.handHoldIdCardUrlList.push({
      //     status: 'success',
      //     message: '',
      //     url: this.qiNiuImgURL + getApp().formatImageSuffix(this.merchantDetail.handHoldIdCard)
      //   })
      // }
      // 收银台照
      this.checkStandPhotoAndHandHoldIdCard()
    },

    submit(){
      try {
        this.$refs.storeInfoForm.validate().then(res => {
          this.updateUncommittedMerchantInfo()

          uni.showLoading({
            title: '加载中...',
            mask: true
          })
          this.$api('merchant.merchantRegisterByApplet', this.merchantDetail).then(res => {
            if (res.status == 0) {
              this.$helpers.toast('提交成功，预计一小时内有审核结果', 'none', 4000, true, () => {
                uni.switchTab({
                  url: '/pages/home/home',
                  success (){
                    // uni.navigateTo({
                    //   url: '/pages-merchant/list/list'
                    // })
                  }
                })
              });
            } else {
              uni.hideLoading();
              getApp().err("提交不成功，" + res.msg);
            }
          }).catch((err) => {
            uni.hideLoading();
            getApp().err('提交不成功，' + err)
          })
        }).catch(errors => {
          getApp().err('请按红色文字提示输入完整信息才能进行下一步')
        })
      } catch (e) {
        console.error(e.toString())
        getApp().err('提交不成功：' + e.toString())
      }
    },

    async photoUploadAfterRead(event) {
		  uni.showLoading({
			title: '上传中',
			mask: true
		  })
		// #ifndef H5
		let _this = this;
		if(event.file.size > 1024000){
			uni.compressImage({
				src: event.file.url,
				quality: 60,
				success: comRes => {
					_this.photoUploadAfterReadFun(event,comRes.tempFilePath);
				}
			})
		}else{
			this.photoUploadAfterReadFun(event,event.file.url);
		}
		// #endif
		
		// #ifdef H5
		this.photoUploadAfterReadFun(event,event.file.url);
		// #endif
      
    },
	async photoUploadAfterReadFun(event,fileUrl) {
	 const item = {
        url: fileUrl,
        status: 'uploading',
        message: '上传中'
      }

      if (event.name == this.photoTypeEnum.shopPhoto){
        this.shopPhotoUrlList.push(item);

        this.photoUploadFilePromise(fileUrl, null).then((res) => {
          this.merchantDetail.shopPhoto = res.data.picture;

          const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
          this.shopPhotoUrlList.splice(0, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: url
          }))

          this.checkShopPhotoAndShopEntrancePhoto(true);
        }).catch((err) => {
          console.error("shopPhotoCatch", err)
          this.shopPhotoUrlList.splice(0, 1);
        })
      } else if (event.name == this.photoTypeEnum.shopEntrancePhoto){
        this.shopEntrancePhotoUrlList.push(item);

        this.photoUploadFilePromise(fileUrl, null).then((res) => {
          this.merchantDetail.shopEntrancePhoto = res.data.picture;

          const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
          this.shopEntrancePhotoUrlList.splice(0, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: url
          }))

          this.checkShopPhotoAndShopEntrancePhoto(true);
        }).catch((err) => {
          console.error("shopEntrancePhotoCatch", err)
          this.shopEntrancePhotoUrlList.splice(0, 1);
        })
      } else if (event.name == this.photoTypeEnum.checkStandPhoto){
        this.checkStandPhotoUrlList.push(item);

        this.photoUploadFilePromise(fileUrl, null).then((res) => {
          this.merchantDetail.checkStandPhoto = res.data.picture;

          const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
          this.checkStandPhotoUrlList.splice(0, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: url
          }))

          this.checkStandPhotoAndHandHoldIdCard(true);
        }).catch((err) => {
          console.error("checkStandPhotoCatch", err)
          this.checkStandPhotoUrlList.splice(0, 1);
        })
      } else if (event.name == this.photoTypeEnum.handHoldIdCard){
        this.handHoldIdCardUrlList.push(item);

        this.photoUploadFilePromise(fileUrl, null).then((res) => {
          this.merchantDetail.handHoldIdCard = res.data.picture;

          const url = this.qiNiuImgURL + getApp().formatImageSuffix(res.data.picture);
          this.handHoldIdCardUrlList.splice(0, 1, Object.assign(item, {
            status: 'success',
            message: '',
            url: url
          }))

          this.checkStandPhotoAndHandHoldIdCard(true);
        }).catch((err) => {
          console.error("handHoldIdCardCatch", err)
          this.handHoldIdCardUrlList.splice(0, 1);
        })
      } else {
        uni.hideLoading();
        this.$helpers.toast("e.name有误");
        return
      }
	
	  
	},

    photoUploadFilePromise(fileUrl, photoType) {
      // console.log("photoType", photoType)
      return new Promise((resolve, reject) => {
        let a = uni.uploadFile({
          url: this.$configPath.baseURL + '/api/merchant/merchantRegisterUploadByApplet',
          filePath: fileUrl,
          name: 'file',
          header: {
            Authorization: 'Bearer ' + this.$store.getters.GET_VALUE("GET_TOKEN")
          },
          timeout: 6000,
          formData: {
            photoType: photoType
          },
          success: (res) => {
            uni.hideLoading();
            let data = JSON.parse(res.data);
            if (this.merchantInfoUploadStateEnum.SUCCESS == data.status) {
              this.$helpers.toast("上传成功", "success");
              resolve(data);
            } else if (this.merchantInfoUploadStateEnum.FAILURE_TO_IDENTIFY == data.status){
              //上传成功，识别失败
              resolve(data);
            } else {
              reject(data)
              getApp().err("上传不成功，" + data.msg);
            }
          },
          fail: (res) => {
            uni.hideLoading();
            let errMsg = res.errMsg;
            if (uni.$u.test.contains(errMsg, 'timeout')) {
              errMsg = "请求超时，请重新上传";
            }
            getApp().err(errMsg);
            reject("请求超时，请重新上传")
          },
        });
      })
    },

    bannerOversize() {
      getApp().err("图片大小超限，最大3MB。如图片来自相册，建议使用直接拍摄");
    },

    deletePhoto(photoType){
      try {
        if (photoType == this.photoTypeEnum.shopPhoto){
          this.merchantDetail.shopPhoto = "";
          this.shopPhotoUrlList.splice(0, 1)
        } else if (photoType == this.photoTypeEnum.shopEntrancePhoto){
          this.merchantDetail.shopEntrancePhoto = "";
          this.shopEntrancePhotoUrlList.splice(0, 1)
        } else if (photoType == this.photoTypeEnum.checkStandPhoto){
          this.merchantDetail.checkStandPhoto = "";
          this.checkStandPhotoUrlList.splice(0, 1)
        }
        // else if (photoType == this.photoTypeEnum.handHoldIdCard){
        //   this.merchantDetail.handHoldIdCard = "";
        //   this.handHoldIdCardUrlList.splice(0, 1)
        // }
        else {
          getApp().err("图片类型有误")
        }
        this.checkShopPhotoAndShopEntrancePhoto(true);
        this.checkStandPhotoAndHandHoldIdCard(true);
      } catch (e){
        console.error(e.toString())
        this.$helpers.toast("删除不成功");
      }
    },

    checkShopPhotoAndShopEntrancePhoto(checked){
      if (
          !this.$u.test.isEmpty(this.merchantDetail.shopPhoto)
          && !this.$u.test.isEmpty(this.merchantDetail.shopEntrancePhoto)
      ){
        this.merchantDetail.shopPhotoAndShopEntrancePhoto = true;
      } else {
        this.merchantDetail.shopPhotoAndShopEntrancePhoto = false;
      }

      if (checked){
        this.shopPhotoAndShopEntrancePhotoValidateField();
      }
    },

    checkStandPhotoAndHandHoldIdCard(checked){
      if (
          !this.$u.test.isEmpty(this.merchantDetail.checkStandPhoto)
          // && !this.$u.test.isEmpty(this.merchantDetail.handHoldIdCard)
      ){
        this.merchantDetail.checkStandPhotoAndHandHoldIdCard = true;
      } else {
        this.merchantDetail.checkStandPhotoAndHandHoldIdCard = false;
      }

      if (checked){
        this.checkStandPhotoAndHandHoldIdCardValidateField();
      }
    },

    shopPhotoAndShopEntrancePhotoValidateField(){
      this.$refs.storeInfoForm.validateField('shopPhotoAndShopEntrancePhoto', err => {
        // console.log("err", err)
      })
    },

    checkStandPhotoAndHandHoldIdCardValidateField(){
      this.$refs.storeInfoForm.validateField('checkStandPhotoAndHandHoldIdCard', err => {
        // console.log("err", err)
      })
    },

    // 获取最近一次的记录
    getUncommittedMerchantInfo(){
      this.$api('merchant.getUncommittedMerchantInfo', null).then(res => {
        if (res.status == 0) {
          if (!this.$u.test.isEmpty(res.data)){
            this.initData(res.data);
          }
        }
      }).catch((e) => {
		getApp().err("获取失败，" + e);
        uni.hideLoading();
      })
    },

    // 更新记录
    updateUncommittedMerchantInfo(){
      this.$api('merchant.updateUncommittedMerchantInfo', this.merchantDetail).then(res => {
        if (res.status == 0) {}
      }).catch((e) => {
		getApp().err("更新失败，" + e);
        uni.hideLoading();
      })
    },

  }
}
</script>

<style lang="scss" scoped>

.main{
  .content{
    .content-item{
      background-color: $uni-bg-color;
      margin-bottom: 20rpx;
      padding: 24rpx 30rpx;

      .content-title{
        color: rgb(13, 13, 13);
        font-size: 30rpx;
      }

      .upload{
        //padding: 10rpx 0rpx 12rpx ;
      }
    }
  }

  .footer{
    width: 100%;
    margin-top: 94rpx;
    padding-bottom: 74rpx;
  }
}

/deep/ .u-upload__wrap__preview {
  margin: 0 8px 0px 0 !important;
}
</style>
